package com.mrzhang.glpt.gateway.common.config;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.exception.NacosException;
import com.mrzhang.glpt.gateway.common.entity.ZuulRouteEntity;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.cloud.netflix.zuul.filters.ZuulProperties;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@Component
@Slf4j
@RefreshScope
public class PropertiesAssemble{

    @Autowired
    private ConfigService configService;


    @Value("${nacos.route.dataid}")
    private   String NACOS_DATA_ID;

    @Value("${nacos.route.groupid}")
    private   String NACOS_GROUP_ID;

    @Value("${nacos.route.refreshtime}")
    private   Long NACOS_REFRESH_TIME;

    public Map<String, ZuulProperties.ZuulRoute> getProperties() {
        Map<String, ZuulProperties.ZuulRoute> routes = new LinkedHashMap<>();
        List<ZuulRouteEntity> results = listenerNacos(NACOS_DATA_ID,NACOS_GROUP_ID);
        for (ZuulRouteEntity result : results) {
            if (StringUtils.isBlank(result.getPath())
                /*|| org.apache.commons.lang3.StringUtils.isBlank(result.getUrl())*/) {
                continue;
            }
            ZuulProperties.ZuulRoute zuulRoute = new ZuulProperties.ZuulRoute();
            try {
                BeanUtils.copyProperties(result, zuulRoute);
            } catch (Exception e) {
            }
            routes.put(zuulRoute.getPath(), zuulRoute);
        }
        return routes;
    }




    private List<ZuulRouteEntity> listenerNacos (String dataId, String group) {
        try {
            String content = configService.getConfig(dataId, group, NACOS_REFRESH_TIME);
            log.info("从Nacos返回的配置：{}",content);
//            System.out.println("从Nacos返回的配置：" + content);
            return JSONObject.parseArray(content, ZuulRouteEntity.class);
        } catch (NacosException e) {
            e.printStackTrace();
        }
        return new ArrayList<>();
    }
}
